<?php
namespace Crm\Api;

use PhalApi\Api;
use Auth\Api\Token as Token;
use Crm\Domain\Score as DomainScore;
use Crm\Domain\WxUser as DomainWxUser;

/**
 * WxUser服务类
 *
 * @author: luodong <751450467@qq.com> 2020-06-24
 */

class WxUser extends Api {

    /**
     * token对象
     */
    public $token;

    /**
     * 当前用户信息
     */
    public $user;

    public function __construct()
    {
        //允许所有域名发起的跨域请求
        header('Access-Control-Allow-Origin: *');  //支持全域名访问，不安全，部署后需要固定限制为客户端网址
        //header('Access-Control-Allow-Methods:POST,GET,OPTIONS,DELETE'); //支持的http 动作
        //header('Access-Control-Allow-Headers:Authorization,content-type');  //响应头 请按照自己需求添加。
        //$this->di = \PhalApi\DI();
        $this->token = new Token();

    }

	public function getRules() {
        return array(
            'userScore' => array(),
            'userInfo' => array(),
            'seriesSignNum' => array('user_id'=> array('name' => 'user_id', 'type'=>'int','default'=>0,'require'=>false,'desc'=>'用户id')),
            'getUserPhone'=>array(),
            'setUserInfo' => array(),
            'setMobile' => array(
                'mobile' => array('name' => 'mobile','type'=>'string','require'=>true,'desc'=>'手机号'),
                'mall_id' => array('name' => 'mall_id','type'=>'int','default'=>0, 'require'=>false,'desc'=>'商城ID')
            ),
            'addHouse' => array(//提交房屋信息(即业主认证)
                'project_id' => array('name' => 'project_id', 'type'=>'int', 'require' => true, 'desc' => '楼盘ID'),
                'mall_id' => array('name' => 'mall_id', 'type'=>'int', 'require' => true, 'desc' => '商城ID'),
                'build_no' => array('name' => 'build_no', 'type'=>'string', 'require' => true, 'desc' => '楼栋号'),
                'unit_no' => array('name' => 'unit_no', 'type'=>'string', 'require' => true, 'desc' => '单元号'),
                'house_no' => array('name' => 'house_no', 'type'=>'string', 'require' => true, 'desc' => '房号')
            ),
            'houseInfo' => array(),
            'houseList'=>array(
                'mall_id'=> array('name' => 'mall_id', 'type'=>'int','require'=>true,'desc'=>'默认商城ID'),
                'project_id'=> array('name' => 'project_id', 'type'=>'int','require'=>false,'desc'=>'项目ID')
            ),
            'setHouseRecommend' => array(
                'mall_id'=> array('name' => 'mall_id', 'type'=>'int','require'=>true,'desc'=>'默认商城ID'),
                'user_house_id' => array('name' => 'user_house_id', 'type'=>'int', 'require' => true, 'desc' => '用户房屋ID'),
                'name' => array('name' => 'name', 'type'=>'string', 'require' => true, 'desc' => '推荐人姓名'),
                'mobile' => array('name' => 'mobile', 'type'=>'string', 'require' => true, 'desc' => '推荐人手机'),
                'code'=> array('name' => 'code', 'type'=>'int','require'=>true,'desc'=>'验证码')
            ),
            'verifyHouse' => array(
                'user_house_id' => array('name' => 'user_house_id', 'type'=>'int', 'require' => true, 'desc' => '用户房屋ID'),
                'owner_uid' => array('name' => 'owner_uid', 'type'=>'int', 'require' => true, 'desc' => '业主ID'),
                'status' => array('name' => 'status', 'type'=>'enum', 'require' => true,'range'=>array('0','1','9'), 'desc' => '审核状态0:待审核 1:通过 9:不通过'),
                'des' => array('name' => 'des', 'type'=>'string', 'require' => false, 'desc' => '审核意见'),
                'code'=> array('name' => 'code', 'type'=>'int','require'=>true,'desc'=>'验证码')
            ),
            'verifyRecommend' => array(
                'project_id' => array('name' => 'project_id', 'type'=>'int', 'require' => true, 'desc' => '楼盘ID'),
                'mall_id' => array('name' => 'mall_id', 'type'=>'int', 'require' => true, 'desc' => '商城ID'),
                'mobile' => array('name' => 'mobile', 'type'=>'int', 'require' => true, 'desc' => '手机号')
            ),
            'attent' => array(
                'action_id'     => array('name' => 'action_id', 'type'=>'int', 'require' => true, 'desc' => '关注主体ID'),
                'action' => array('name' => 'action', 'type'=>'string', 'require' => true, 'desc' => '关注主体'),
                'type'=>array('name' => 'type', 'type'=>'enum', 'require' => true, 'range'=>array('info','price','open'), 'default'=>'info', 'desc' => '关注主体类型[默认info:主体，price:价格，open:开盘]'),
                'opt' => array('name' => 'opt', 'type'=>'enum', 'require' => true, 'range' => array('cancel','sure'), 'desc' => '关注或取消')
            ),
            'isAttent' =>array(
                'action_id'     => array('name' => 'action_id', 'type'=>'int', 'require' => true, 'desc' => '关注主体ID'),
                'action' => array('name' => 'action', 'type'=>'string', 'require' => true, 'desc' => '关注主体'),
                'type'=>array('name' => 'type', 'type'=>'enum', 'require' => true, 'range'=>array('info','price','open'), 'default'=>'info', 'desc' => '关注主体类型[默认info:主体，price:价格，open:开盘]')
            ),
            'scoreList'=>array(
                'mall_id'=> array('name' => 'mall_id', 'type'=>'int','require'=>true,'desc'=>'默认商城ID')
            ),
            'awardList'=>array(
                'mall_id'=> array('name' => 'mall_id', 'type'=>'int','require'=>true,'desc'=>'默认商城ID')
            ),
            'awardGive'=>array(
                'user_award_id'=> array('name' => 'user_award_id', 'type'=>'int','require'=>true,'desc'=>'用户兑奖ID'),
                'code'=> array('name' => 'code', 'type'=>'int','require'=>true,'desc'=>'兑奖码')
            )
        );
	}

    /**
     * 统计用户积分
     * @desc 返回用户相关信息
     * @return array userInfo 用户信息
     * @return int time 当前时间戳
     */
    public function userScore(){
        $this->user = $this->token->checkToken();
        $domain = new DomainScore();
        $score = $domain->countUserScore($this->user['user_id']);
        return $score;
    }

    /**
     * 获取用户信息
     * @desc 返回用户相关信息
     * @return array userInfo 用户信息
     * @return int time 当前时间戳
     */
    public function userInfo(){
        $this->user = $this->token->checkToken();
        $domain = new DomainWxUser();
        $info = $domain->getUserInfo($this->user['user_id']);
        return $info;
    }

    /**
     * 连续签到天数
     * @desc 连续签到天数
     * @return int seriesSignNum 连续签到天数
     * @return int time 当前时间戳
     */
    public function seriesSignNum(){
        $domain = new DomainScore();
        $data['seriesSignNum'] = $domain->seriesSignNum($this->user_id);
        return $data;
    }

    /**
     * 设置用户信息
     * @desc 返回用户相关信息
     * @return array userInfo 用户信息
     * @return int time 当前时间戳
     */
    public function setUserInfo() {
        $this->user = $this->token->checkToken();
        error_log("setUserInfo!", 0);

        $params =  \PhalApi\DI()->request->getAll();
        $user = new DomainWxUser();
        $id = $user->update($params,$this->user["user_id"]);

        return $id;
    }

    /**
     * 设置用户电话
     * @desc 设置用户电话
     * @return int user_id 用户id
     * @return int time 当前时间戳
     */
    public function setMobile() {
        $this->user = $this->token->checkToken();
        error_log("setmobile!", 0);

        $params =  \PhalApi\DI()->request->getAll();
        $user = new DomainWxUser();
        $id = $user->update($params,$this->user["user_id"]);

        //首次绑定手机即可积分
        $score = new DomainScore();
        $isObtain = $score->checkObtainScore($this->user['user_id'],'2020308','wx_user',$this->user["user_id"],$this->mall_id);
        if($isObtain) $score->addScore($this->user["user_id"],'2020308','wx_user',$this->user["user_id"],$this->mall_id);

        return $id;
    }

    /**
     * 用户关注
     * @desc 用户关注
     * @return array data 关注结果
     * @return int time 当前时间戳
     */
    public function attent(){
        $this->user = $this->token->checkToken();
        error_log("attent!", 0);

        $params =  \PhalApi\DI()->request->getAll();
        $domain = new DomainWxUser();
        $data = $domain->attent($this->user['user_id'],$params, $this->opt);
        return $data;
    }

    /**
     * 用户是否关注
     * @desc 用户是否关注
     * @return array data 用户是否关注
     * @return int time 当前时间戳
     */
    public function isAttent(){
        $this->user = $this->token->checkToken();
        error_log("isAttent!", 0);
        $params =  \PhalApi\DI()->request->getAll();
        $domain = new DomainWxUser();
        $result = $domain->isAttent($this->user['user_id'],$params);
        return $result;
    }


    /**
     * 用户房屋列表
     * @desc 用户房屋列表
     * @return object list 用户房屋列表
     * @return int time 当前时间戳
     */
    public function houseList(){
        $this->user = $this->token->checkToken();
        error_log("houseList!", 0);

        $param = \PhalApi\DI()->request->getAll();
        $domain = new DomainWxUser();
        $data = $domain->houseList($param);
        return $data;
    }

    /**
     * 用户房屋添加
     * @desc 用户添加房屋（即业主认证）
     * @return array data 用户添加的房屋（即业主认证）信息
     * @return int time 当前时间戳
     */
    public function addHouse(){
        $this->user = $this->token->checkToken();
        error_log("attent!", 0);

        $params =  \PhalApi\DI()->request->getAll();
        $domain = new DomainWxUser();
        $data = $domain->addHouse($this->user['user_id'],$params);
        return $data;
    }

    /**
     * 用户房屋认证信息
     * @desc 用户房屋认证信息
     * @return array data 用户房屋认证信息
     * @return int time 当前时间戳
     */
    public function houseInfo(){
        $this->user = $this->token->checkToken();
        error_log("attent!", 0);

        $params =  \PhalApi\DI()->request->getAll();
        $domain = new DomainWxUser();
        $data = $domain->houseInfo($this->user['user_id'],$params);
        return $data;
    }

    /**
     * 设置用户房屋推荐人
     * @desc 设置用户房屋推荐人
     * @return object data 设置用户房屋推荐人结果
     * @return int time 当前时间戳
     */
    public function setHouseRecommend(){
        $this->user = $this->token->checkToken();
        $param = \PhalApi\DI()->request->getAll();
        if($param['code']=='666888') {
            $domain = new DomainWxUser();
            $data = $domain->setHouseRecommend($this->user['user_id'], $param);
        }else{
            $data = array('status' => 200, 'msg' => '验证码错误!');
        }
        return $data;
    }

    /**
     * 用户房屋审核(业主认证)
     * @desc 用户兑换
     * @return object data 用户兑换结果
     * @return int time 当前时间戳
     */
    public function verifyHouse(){
        $this->user = $this->token->checkToken();
        $param = \PhalApi\DI()->request->getAll();
        if($param['code']=='666888') {
            $domain = new DomainWxUser();
            $data = $domain->verifyHouse($this->user['user_id'], $param);
        }else{
            $data = array('status' => 200, 'msg' => '验证码错误!');
        }
        return $data;
    }

    /**
     * 老带新推荐认证
     * @desc 老带新推荐认证
     * @return array data 老带新推荐认证
     * @return int time 当前时间戳
     */
    public function verifyRecommend(){
        $this->user = $this->token->checkToken();
        error_log("attent!", 0);

        $params =  \PhalApi\DI()->request->getAll();
        $domain = new DomainWxUser();
        $data = $domain->verifyRecommend($this->user['user_id'],$params);
        return $data;
    }

    /**
     * 得到用户微信电话
     * @desc 返回用户微信电话
     * @return obj data 用户电话
     * @return int time 当前时间戳
     */
    public function getUserPhone() {
        // 接收信息
        $params = \PhalApi\DI()->request->getAll();
        $encryptedData = $params['encryptedData']; // 加密数据
        $iv = $params['iv']; // 加密算法
        $this->sessionKey = $params['sessionKey']; // 会话密钥
        if($encryptedData == '' || $iv == ''){
            error_log("手机号码没获取!", 0);
        }else{
            $rlt = $this->decryptData($encryptedData, $iv);
        }
        return $rlt;
    }

    /**
     * 用户积分列表
     * @desc 用户积分列表
     * @return object list 用户积分列表
     * @return int time 当前时间戳
     */
    public function scoreList(){
        $this->user = $this->token->checkToken();
        $param = \PhalApi\DI()->request->getAll();
        $param['user_id'] = $this->user['user_id'];
        $domain = new DomainScore();
        $data = $domain->search($param);
        return $data;
    }


    /**
     * 用户列表
     * @desc 用户列表
     * @return object list 用户列表
     * @return int time 当前时间戳
     */
    public function awardList(){
        $this->user = $this->token->checkToken();
        $param = \PhalApi\DI()->request->getAll();
        $param['user_id'] = isset($param['user_id'])?$param['user_id']:$this->user['user_id'];
        $domain = new DomainWxUser();
        $data = $domain->awardList($param);
        return $data;
    }

    /**
     * 用户领取奖品
     * @desc 用户领取奖品
     * @return object data 用户领取奖品结果
     * @return int time 当前时间戳
     */
    public function awardGive(){
        $this->user = $this->token->checkToken();
        $param = \PhalApi\DI()->request->getAll();
        if($param['code']=='666888') {
            $domain = new DomainWxUser();
            $data = $domain->awardGive($this->user['user_id'], $param);
        }else{
            $data = array('status' => 200, 'msg' => '兑奖码错误!');
        }
        return $data;
    }

    /**
     * 检验数据的真实性，并且获取解密后的明文.
     * @param $encryptedData string 加密的用户数据
     * @param $iv string 与用户数据一同返回的初始向量
     * @param $data string 解密后的原文
     *
     * @return int 成功0，失败返回对应的错误码
     */
    public function decryptData( $encryptedData, $iv)
    {
        if (strlen($this->sessionKey) != 24) {
            error_log("getPhone!", 0);
        }
        $aesKey=base64_decode($this->sessionKey);

        if (strlen($iv) != 24) {
            error_log("getPhone!", 0);
        }
        $aesIV=base64_decode($iv);

        $aesCipher=base64_decode($encryptedData);

        $result=openssl_decrypt( $aesCipher, "AES-128-CBC", $aesKey, 1, $aesIV);

        $dataObj=json_decode( $result );

        return $dataObj;
    }


}
